﻿using CCWin;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WebSocketChat.Common;
using WebSocketChat.Common.Client;
using Newtonsoft.Json;
using CCWin.SkinControl;
using WebSocketChat.Common.Database;

namespace WebSocketChat.Client
{
    public partial class MainWindow : CCSkinMain
    {
        private ClientSocket Current;
        private System.Windows.Forms.Timer NotifyTimer = new System.Windows.Forms.Timer();
        private List<IMessage> HistoryMsg = new List<IMessage>();
        public List<ChatGroup> AllUser;
        bool _status = true;
        public MainWindow(ClientSocket client)
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            Current = client;
            client.MessageArrive += Client_MessageArrive;
            Load += MainWindow_Load;

            NotifyTimer.Interval = 600;
            NotifyTimer.Enabled = false;
            NotifyTimer.Tick += NotifyTimer_Tick;
        }

        private void ChangeUserState(ChatUser user)
        {
            if (AllUser == null || AllUser.Count == 0)
                return;
            bool existsUser = false;
            foreach (var item in AllUser)
            {
                foreach (var u in item.Users)
                {
                    if (u.User.ID == user.ID)
                    {
                        u.User.UserStateID = user.UserStateID;
                        existsUser = true;
                        break;
                    }
                }
            }
            foreach (ChatListItem item in clbFriends.Items)
            {
                foreach (ChatListSubItem sub in item.SubItems)
                {
                    if (sub.ID == user.ID)
                    {
                        sub.Status = (ChatListSubItem.UserStatus)user.UserStateID;
                        existsUser = true;
                        break;
                    }
                }
            }
        }

        private void NotifyTimer_Tick(object sender, EventArgs e)
        {
            if (_status)
                niTaskbar.Icon = Properties.Resources.bitbug_favicon;
            else
                niTaskbar.Icon = Properties.Resources.bitbug_favicon2;

            _status = !_status;
        }

        private void Client_MessageArrive(Common.Server.MessageArriveEventArgs obj)
        {
            if (obj.Message == null)
                return;
            switch (obj.Message.Type)
            {
                case MessageType.Online:
                    var user1 = JsonConvert.DeserializeObject<ChatUser>(obj.Message.Data.ToString());
                    user1.UserStateID = (int)ChatListSubItem.UserStatus.Online;
                    ChangeUserState(user1);
                    break;
                case MessageType.Offline:
                    var user2 = JsonConvert.DeserializeObject<ChatUser>(obj.Message.Data.ToString());
                    user2.UserStateID = (int)ChatListSubItem.UserStatus.OffLine;
                    ChangeUserState(user2);
                    break;
                case MessageType.Friend:
                    AllUser = JsonConvert.DeserializeObject<List<ChatGroup>>(obj.Message.Data.ToString());
                    if (AllUser == null)
                    {
                        AllUser = new List<ChatGroup>();
                    }
                    foreach (var item in AllUser)
                    {
                        ChatListItem lst = new ChatListItem(item.Group.Name, false);
                        lst.Tag = item.Group.ID;
                        foreach (var user in item.Users)
                        {
                            ChatListSubItem sub = new ChatListSubItem(user.NickName, user.User.LoginID, user.User.Intro, (ChatListSubItem.UserStatus)user.User.UserStateID);
                            sub.Tag = user.User.ID;
                            sub.ID = (uint)user.User.ID;
                            sub.PersonalMsg = user.User.SignaTures;
                            string headimagename = System.IO.Path.GetFileNameWithoutExtension(user.User.HeadPortrait);
                            sub.HeadImage = Properties.Resources.ResourceManager.GetObject(headimagename) as Bitmap;
                            lst.SubItems.Add(sub);
                        }
                        clbFriends.Items.Add(lst);
                    }

                    break;
                case MessageType.Chat:
                    this.Invoke(new Action(() =>
                    {
                        bool isopen = false;
                        foreach (var item in Application.OpenForms)
                        {
                            var form = item as ChatForm;
                            if (form != null && form.FormItem.ID == obj.Message.Sender)
                            {
                                form.Show();
                                form.MessageArrive(obj.Message);
                                isopen = true;
                                break;
                            }
                        }
                        if (!isopen)
                        {
                            HistoryMsg.Add(obj.Message);
                            NotifyTimer.Enabled = true;
                        }
                    }));
                    break;
            }
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {

            slName.Text = Current.User.NickName;
            slDesc.Text = Current.User.SignaTures + "(" + Current.User.LoginID + ")";
            IMessage msg = new CommandMessage()
            {
                Type = MessageType.Friend,
                Data = Current.User
            };
            Current.Send(msg);
        }

        private void clbFriends_DoubleClickSubItem(object sender, ChatListEventArgs e, MouseEventArgs es)
        {
            ChatForm chat = null;
            foreach (var item in Application.OpenForms)
            {
                var form = item as ChatForm;
                if (form != null && form.FormItem.Tag == e.MouseOnSubItem.Tag)
                {
                    chat = form;
                    break;
                }
            }
            if (chat == null)
            {
                chat = new ChatForm(e.MouseOnSubItem, Current);
            }
            chat.Show();
        }

        private void niTaskbar_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (NotifyTimer.Enabled)
            {
                foreach (var item in HistoryMsg)
                {
                    ChatForm resForm = null;
                    foreach (var form in Application.OpenForms)
                    {
                        var formchat = form as ChatForm;
                        if (formchat != null && formchat.FormItem.ID == item.Sender)
                        {
                            resForm = formchat;
                        }
                    }
                    if (resForm == null)
                        resForm = new ChatForm(FindSubItem(item.Sender), Current);

                    resForm.Show();
                    resForm.MessageArrive(item);
                }

                NotifyTimer.Enabled = false;
                niTaskbar.Icon = Properties.Resources.bitbug_favicon;
            }
            else
            {
                this.Show();
            }
        }

        private ChatListSubItem FindSubItem(int uid)
        {
            foreach (ChatListItem item in clbFriends.Items)
            {
                foreach (ChatListSubItem sub in item.SubItems)
                {
                    if (sub.ID == uid)
                        return sub;
                }
            }
            return null;
        }

        private void tsShow_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void tsExit_Click(object sender, EventArgs e)
        {
            Current.Close();
            Environment.Exit(0);
        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void spbHeader_Click(object sender, EventArgs e)
        {
            HeadImageForm hif = new HeadImageForm((name) =>
            {
                spbHeader.BackgroundImage = Properties.Resources.ResourceManager.GetObject(name) as Bitmap;
            });
            hif.ShowDialog();
        }
    }
}
